package experimentation

import javax.swing.text.html.HTML;

class UserController {

	
    def index() { }
	
	def login() {
		def allUsers = User.list() 
	}
	
	def AttemptLogin(){
		User currentUser = [userName: params.username, password: params.password]
		render "<div>Attempting to Logon:" + currentUser.userName + "     " + currentUser.password + "</div>"
		Logon(currentUser)
	}
	
	def Logon(User currentUser){
		def user = User.findWhere(userName:currentUser.userName, password:currentUser.password)
		session.user = user
		if (user)
		{
			redirect (uri: "/Home/home")
		}
		else
		{
			redirect (uri: "/User/login")
		}
			
	}
	def Logout() {
		session.user = null
		redirect (uri: "/Home/home")
	}
	
	def GetUser()
	{
		session.user.userName
	}
	
	def Account()
	{
		if(session.user)
		{
			params.myMessage =  WelcomeMessage()
			params.Login = "Welcome, <a href=\"../User/account\">${session.user.userName}</a>  [<a href=\"../User/Logout\">Logout</a>]"
		}
		else
		{
			params.myMessage =  WelcomeMessage()
			params.Login = "Welcome, Guest.  [<a href=\"../User/login\">Login</a>]"
		}
	}
	
	def WelcomeMessage() {
		String txt = "Welcome to the homepage, "
		if(session.user)
		{
			txt += "${session.user.userName}.";
		}
		else
		{
			txt+= "Guest"
		}
	}
	
	def AttemptRegister()
	{
		String error = ""
		User newUser = [userName: params.userName, password: params.password, email: params.email, fullName: params.name]
		if(params.password == params.confirmPassword)
		{
			if(!User.findWhere(userName:params.userName))
			{
				if(newUser.save())
				{
					Logon( newUser)
				}
				else
				{
					error = "Failed to create user."
					flash.error = error
					redirect (uri: "/User/register")
					System.out.println(newUser.errors.toString());
				}
					
				
			}
			else
			{
				error = "User name is unavailable."
				flash.error = error
				redirect (uri: "/User/register")
				System.out.println(newUser.errors.toString());
			}
		}
		else
		{
			error = "Passwords do not match."
			flash.error = error
			redirect (uri: "/User/register")
			System.out.println(newUser.errors.toString());
		}
		
		
	}
	
	def Register(){
	
	}
}
